<template>
    <div class="dictionary-container">
        <div class="dictionary-header">
            <div class="dictionary-title">{{ this.schema.title }}</div>
            <div class="dictionary-description">{{ this.schema.description }}</div>
        </div>
        <div class="dictionary-body">
            <div class="dictionary-items">
                <!-- 动态键值对列表 -->
                <div v-for="(item, index) in items" :key="item.id" class="dictionary-item">
                    <div class="key-value-section">
                        <!-- 键输入 -->
                        <div class="key-section">
                            <div style="margin-right: 5px;">K</div>
                            <el-input class="key-input" size="mini" v-model="item.key" :placeholder="keyPattern"
                                @focus="handleKeyFocus" @blur="handleKeyBlur(item, $event)">
                            </el-input>
                        </div>
                        <!-- 值部分 -->
                        <div class="value-section">
                            <div style="margin-right: 5px;">V</div>
                            <!-- 如果值类型是object或者字典完全复用 VueForm  -->
                            <template v-if="valueSchema.type === 'object'">
                                <div class="value-border">
                                    <vue-form :schema="valueSchema" :ui-schema="valueUiSchema" v-model="item.value"
                                        :formProps="formProps" :formFooter="formFooter"></vue-form>
                                </div>
                            </template>
                            <!-- 如果值类型是array -->
                            <template v-if="valueSchema.type === 'array'">
                                <div class="value-border">
                                    <DictionaryValueArray :schema="valueSchema" :rootFormData="item.value"
                                        :ui-schema="valueUiSchema">
                                    </DictionaryValueArray>
                                </div>
                            </template>
                            <!-- 如果是字符串 -->
                            <template v-else-if="valueSchema.type === 'string'">
                                <el-input class="value-input" size="mini" v-model="item.value"
                                    @change="handleValueChange">
                                </el-input>
                            </template>
                            <!-- 如果是数字 -->
                            <template v-else-if="valueSchema.type === 'integer' || valueSchema.type === 'number'">
                                <el-input-number size="mini" class="value-input" v-model="item.value" placeholder="值"
                                    @change="handleValueChange">
                                </el-input-number>
                            </template>
                            <!-- 如果是布尔 -->
                            <template v-else-if="valueSchema.type === 'boolean'">
                                <el-switch v-model="item.value" @change="handleValueChange" active-color="#13ce66"
                                    inactive-color="#ff4949">
                                </el-switch>
                            </template>

                        </div>
                    </div>
                    <div class="item-actions">
                        <el-button class="delete-button" size="mini" type="danger" icon="el-icon-delete"
                            @click="removeItem(index)" />
                    </div>
                </div>
            </div>

            <div class="add-button">
                <el-button size="mini" type="primary" icon="el-icon-plus" @click="addItem">
                    添加键值对
                </el-button>
            </div>
        </div>

    </div>
</template>

<script>
import VueForm from '@lljj/vue-json-schema-form'
import { fieldProps, vueUtils } from '@lljj/vue-json-schema-form'
import DictionaryValueArray from './DictionaryValueArray.vue'

export default {
    name: 'DictionaryField',
    components: {
        VueForm,
        DictionaryValueArray
    },
    props: {
        ...fieldProps,
        // 增强props
        uiSchema: {
            type: Object,
            default: () => ({})
        },
    },
    data() {
        return {
            formFooter: {
                show: false, // 是否显示默认底部
                okBtn: '保存', // 确认按钮文字
                cancelBtn: '取消' // 取消按钮文字
            },
            items: this.normalizeInitialData(),
            oldKey: '', // 存储当前选中的key输入框的旧值
        }
    },
    created() {

    },
    mounted() {
        setTimeout(() => {
            this.updateFormData()
        }, 0)
    },

    computed: {
        // 从patternProperties提取值schema
        valueSchema() {
            const patterns = this.schema.patternProperties || {}
            return Object.values(patterns)[0] || { type: 'string' }
        },

        // 提取值的ui配置
        valueUiSchema() {
            const patternKeys = Object.keys(this.uiSchema.patternProperties || {})
            return patternKeys.length
                ? this.uiSchema.patternProperties[patternKeys[0]]
                : {}
        },

        // 键名验证正则
        keyPattern() {
            const patterns = Object.keys(this.schema.patternProperties || {})
            return patterns[0] ? new RegExp(patterns[0]) : /^.*$/
        },
    },
    methods: {
        // 初始化数据处理
        normalizeInitialData() {
            const formData = vueUtils.getPathVal(this.rootFormData, this.curNodePath) || {}
            return Object.entries(formData).map(([key, value]) => {
                if (Object.values(this.schema.patternProperties)[0].type == 'array') {
                    formData[key] = JSON.parse(value)
                    return {
                        id: `${key}_${Date.now()}`,
                        key,
                        value: JSON.parse(value)
                    }
                } else {
                    return {
                        id: `${key}_${Date.now()}`,
                        key,
                        value
                    }
                }

            })
        },

        // 获取值字段的路径
        getValuePath(index) {
            return `${this.curNodePath}.${this.items[index].key}`
        },

        // 添加新项
        addItem() {
            // 如果items中有""key,不让添加
            if (this.items.some(item => item.key === '')) {
                this.$message.error('请先填写key为空的项')
                return
            }
            this.items.push({
                id: `new_${Date.now()}`,
                key: '',
                value: this.getDefaultValue()
            })
            this.updateFormData();

        },

        // 根据schema类型获取默认值
        getDefaultValue() {
            switch (this.valueSchema.type) {
                case 'object': return {}
                case 'array': return []
                case 'number': return 0
                case 'boolean': return true
                default: return ''
            }
        },

        // 删除项
        removeItem(index) {
            this.items.splice(index, 1)
            this.updateFormData()
        },

        handleKeyFocus(event) {
            this.oldKey = event.target.value;
        },

        handleKeyBlur(item, event) {
            const newKey = event.target.value;
            if (this.oldKey == newKey) return;
            // 1.验证键名是否符合 patternProperties 的正则
            const isValid = this.keyPattern.test(newKey);
            if (!isValid) {
                this.$message.error('请填写符合当前正则的键名：' + this.keyPattern);
                item.key = this.oldKey; // 重置为原键名
                return;
            }
            // 获取所有的键名
            const keys = this.items.map(item => item.key);
            // 2.检查键名是否已存在
            if (keys.filter(item => item === newKey).length > 1) {
                this.$message.error('键名已存在');
                item.key = this.oldKey; // 重置为原键名
                return;
            }
            this.updateFormData();
        },

        handleValueChange(event) {
            this.updateFormData();
        },

        // 更新表单数据
        updateFormData() {
            // 将数组转换回对象格式
            const newValue = this.items.reduce((acc, { key, value }) => {
                if (key) acc[key] = value;
                return acc;
            }, {});
            if (this.curNodePath === "") {
                // 清空对象值（引用不变）
                for (let key in this.rootFormData) {
                    if (this.rootFormData.hasOwnProperty(key)) {
                        delete this.rootFormData[key];
                    }
                }
                // 添加值
                for (let key in newValue) {
                    if (newValue.hasOwnProperty(key)) {  // 确保只处理对象自身的属性
                        this.rootFormData[key] = newValue[key];
                    }
                }
            } else {
                vueUtils.setPathVal(this.rootFormData, this.curNodePath, newValue);
            }
        },

    },
}
</script>

<style scoped>
.dictionary-container {
    margin-bottom: 50px;

}

.dictionary-title {
    display: block;
    width: 100%;
    line-height: 26px;
    margin-bottom: 8px;
    font-size: 15px;
    font-weight: 700;
    border: 0;
}

.dictionary-description {
    font-size: 12px;
    line-height: 20px;
    margin-bottom: 10px;
    color: #999;
}

.dictionary-body {
    border: 1px solid var(--ui-border-color-base);
    border-radius: 4px;
    padding: 12px;
    background-color: var(--ui-component-background);
}

.dictionary-items {

    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
}

.dictionary-item {
    display: flex;
    margin-bottom: 12px;
    margin-right: 20px;
}

.key-value-section {
    display: flex;
    align-items: flex-start;
}

.item-actions {
    display: flex;
    align-items: flex-start;
}

.key-section,
.value-section,
.delete-button {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-right: 10px;
}

.value-border {
    border: 1px solid var(--ui-border-color-base);
    border-radius: 4px;
    padding: 12px;
}

.add-button {
    display: flex;
    align-items: center;
    justify-content: flex-end;
}

.el-input>>>.el-input__prefix {
    display: flex;
    justify-content: center;
    align-items: center;
}

/* 适配不同表单元素的样式 */
.key-value-section>>>.el-input,
.key-value-section>>>.el-input-number,
.key-value-section>>>.el-select {
    width: 160px;
}
</style>